﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MailSlot
{
    public class MailslotServer : IDisposable
    {
        private Mailslot.SafeMailslotHandle _handle;

        public MailslotServer(string name)
        {
            _handle = Mailslot.CreateMailslot(@"\\.\mailslot\" + name, 0, 0, IntPtr.Zero);
            if (_handle.IsInvalid) throw new Win32Exception();
        }

        public string GetNextMessage()
        {
            int messageBytes;
            int bytesRead;
            int messages;

            if (!Mailslot.GetMailslotInfo(_handle, IntPtr.Zero, out messageBytes,
                         out messages, IntPtr.Zero)) throw new Win32Exception();

            if (messageBytes == Mailslot.MailslotNoMessage) return null;

            var bBuffer = new byte[messageBytes];

            if (!Mailslot.ReadFile(_handle, bBuffer, messageBytes, out bytesRead,
                 IntPtr.Zero) || bytesRead == 0) throw new Win32Exception();

            return Encoding.Unicode.GetString(bBuffer);
        }

        public void Dispose()
        {
            if (_handle != null)
            {
                _handle.Close();
                _handle = null;
            }
        }
    }
}
